from os import popen
import loggers
import os
logger = loggers.loggers('rpc', 'rpc.log', 'INFO', True)

PLUGIN_DIR = os.path.expanduser('~/.sms-middleware/plugins/spam_filter')

global_index = None

def store_message_reply(index):
    global global_index
    index = global_index
    logger.info('SMS stored index=%s' % (global_index))


def plugin_rpc(index, status, sim_number, text, interfaces):
    global global_index
    if text[:4].upper() == 'RPC ':
        cmd = text[4:]
        logger.info('command=%s ready for execution' % cmd)
        logger.info('response mode ON')
        p = popen(cmd)
        s = p.readlines()
        p.close()
        ret_data = ' | '.join(s)
        
        logger.info('ret_data=%s' % ret_data)
        
        resp_sms_list = []
        while True:
            sms = ret_data[:160]
            if sms:
                if interfaces.has_key('org.freesmartphone.GSM.SIM'):
                    interfaces['org.freesmartphone.GSM.SIM'].StoreMessage(
                        recipient_number=sim_number,
                        contents=sms,
                        reply_handler=store_message_reply,
                        error_handler=lambda x:logger.error('Could not store SMS, err=%s' % (x))
                    )
                    if global_index:
                        interfaces['org.freesmartphone.GSM.SIM'].SendStoredMessage(
                            global_index,
                            error_handler=lambda x:logger.info('SMS send as ref=%s' % (x)),
                            error_handler=lambda x:logger.error('Could not send SMS, err=%s' % (x)),
                        )
                    interfaces['org.freesmartphone.GSM.SIM'].DeleteMessage(
                        global_index,
                        reply_handler=lambda:logger.info('SMS index=%s removed' % (index)),
                        error_handler=lambda x:logger.error('Could not remove SMS err=%s' % (x))
                    )
                ret_data = ret_data[160:]
            else:
                break
        
    elif text[:4].upper() == 'RPCN ':
        cmd = text[4:]
        logger.info('command=%s ready for execution' % cmd)
        logger.info('response mode OFF')
        p = popen(cmd)
        p.readlines()
        p.close()
        logger.info('ret_data=%s' % ret_data)
        
        